package com.zhouqinuan.spring.cloud.develop.framework.demo.redis.service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhouqinuan.spring.cloud.develop.framework.base.util.BeanUtil;
import com.zhouqinuan.spring.cloud.develop.framework.demo.redis.constant.RedisKey;
import com.zhouqinuan.spring.cloud.develop.framework.demo.redis.mapper.ext.UserInfoExtMapper;
import com.zhouqinuan.spring.cloud.develop.framework.demo.redis.model.UserInfo;
import com.zhouqinuan.spring.cloud.develop.framework.demo.redis.req.AddUserReq;
import com.zhouqinuan.spring.cloud.develop.framework.demo.redis.req.GetUserInfoByIdReq;
import com.zhouqinuan.spring.cloud.develop.framework.demo.redis.req.UpdateUserReq;
import com.zhouqinuan.spring.cloud.develop.framework.demo.redis.resp.GetUserInfoByIdResp;
import com.zhouqinuan.spring.cloud.develop.framework.redis.util.RedisUtil;

@Service
public class UserService {

    @Autowired
    private UserInfoExtMapper userInfoExtMapper;

    @Autowired
    private RedisUtil redisUtil;

    public GetUserInfoByIdResp getUserInfoById(GetUserInfoByIdReq reqVO) {

        UserInfo userInfo = redisUtil.get(RedisKey.USER_INFO_KEY_PREFIX + reqVO.getUid());
        if (userInfo == null) {
            userInfo = userInfoExtMapper.selectByPrimaryKey(reqVO.getUid());
            redisUtil.set(RedisKey.USER_INFO_KEY_PREFIX + reqVO.getUid(), userInfo, 1, TimeUnit.HOURS);
        }

        return BeanUtil.mapToObject(userInfo, GetUserInfoByIdResp.class);
    }

    public int addUser(AddUserReq reqVO) {
        UserInfo userInfo = BeanUtil.mapToObject(reqVO, UserInfo.class);
        userInfo.setStatus(1);
        userInfo.setCreateTime(new Date());
        return userInfoExtMapper.insertSelective(userInfo);
    }

    public int updateUser(UpdateUserReq reqVO) {
        UserInfo userInfo = BeanUtil.mapToObject(reqVO, UserInfo.class);
        userInfo.setUpdateTime(new Date());
        int rlt = userInfoExtMapper.updateByPrimaryKeySelective(userInfo);
        redisUtil.delete(RedisKey.USER_INFO_KEY_PREFIX + reqVO.getUid());

        return rlt;
    }

    public List<UserInfo> selectAll() {
        List<UserInfo> userInfos = redisUtil.get(RedisKey.USER_INFO_ALL_KEY);
        if (CollectionUtils.isEmpty(userInfos)) {
            userInfos = userInfoExtMapper.selectAll();
            redisUtil.set(RedisKey.USER_INFO_ALL_KEY, userInfos, 1, TimeUnit.HOURS);
        }

        return userInfos;
    }
}
